import React, { Component } from 'react';

class Carousel extends Component {
  constructor(props) {
    super(props)
    this.state = {
      activeIndex: 0
    }
  }
  toPage(i) {
    this.setState({
      activeIndex: i
    })
  }
  prevPage() {
    this.setState({
      activeIndex: this.state.activeIndex > 0 ? (this.state.activeIndex - 1) : (this.props.banner.length - 1)
    })
  }
  nextPage() {
    this.setState({
      activeIndex: this.state.activeIndex < (this.props.banner.length - 1) ? (this.state.activeIndex + 1) : 0
    })
  }
  render() {
    const banner = this.props.banner,
    activeIndex = this.state.activeIndex
    return (
      <div id="carouselExampleIndicators" className="carousel slide mt-2 mb-2" data-ride="carousel">
        <ol className="carousel-indicators">
        {
          banner.map((item, i) => (
            <li key={i} onClick={this.toPage.bind(this, i)} data-target="#carouselExampleIndicators" data-slide-to={i} className={activeIndex === i ? 'active' : ''}></li>
          ))
        }
        </ol>
        <div className="carousel-inner">
        {
          banner.map((item, i) => (
            <div key={i} className={activeIndex === i ? 'carousel-item active' : 'carousel-item'}>
              <img className="d-block w-100" src={item.cover_img} alt="First slide"/>
            </div>
          ))
        }
        </div>
        <a onClick={this.prevPage.bind(this)} className="carousel-control-prev" href="javascript:void(0);" role="button" data-slide="prev">
          <span className="carousel-control-prev-icon" aria-hidden="true"></span>
          <span className="sr-only">Previous</span>
        </a>
        <a onClick={this.nextPage.bind(this)} className="carousel-control-next" href="javascript:void(0);" role="button" data-slide="next">
          <span className="carousel-control-next-icon" aria-hidden="true"></span>
          <span className="sr-only">Next</span>
        </a>
      </div>
    )
  }
}

export default Carousel